package com.soso.base.util.search;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

import com.soso.base.util.log.Logger;

public class SearchBeanUtil {
	
	public static void copyBean(Object dest,Object orig){
		try {
			BeanUtils.copyProperties(dest, orig);
		} catch (IllegalAccessException e) {
			Logger.error(e.getMessage());
		} catch (InvocationTargetException e) {
			Logger.error(e.getMessage());
		}
	}
	public static void initBean(Object ob,HttpServletRequest request){
		try {
			Field[] fields=ob.getClass().getDeclaredFields();
			for(Field field:fields){
				String fieldName=field.getName();
				String type=field.getType().getSimpleName();
				if(type.equals("String")||
						type.equals("Long")||
						type.equals("Integer")||
						type.equals("Boolean")||
						type.equals("Double")
						){
					BeanUtils.setProperty(ob, fieldName, request.getParameter(fieldName));
				}else if(type.equals("String[]")){
					BeanUtils.setProperty(ob, fieldName, request.getParameterValues(fieldName));
				}
			}
		} catch (IllegalAccessException e) {
			Logger.error(e.getMessage());
		} catch (InvocationTargetException e) {
			Logger.error(e.getMessage());
		}
	}
	@SuppressWarnings("unchecked")
	public static <T> T cloneBean(T t){
		T cloneOb=null;
		try {
			cloneOb = (T)BeanUtils.cloneBean(t);
		} catch (IllegalAccessException e) {
			Logger.error(e.getMessage());
		} catch (InstantiationException e) {
			Logger.error(e.getMessage());
		} catch (InvocationTargetException e) {
			Logger.error(e.getMessage());
		} catch (NoSuchMethodException e) {
			Logger.error(e.getMessage());
		}
		return cloneOb;
	}
}
